<template>
  <div class="comment-section">
    <h3 class="comment-section-title">评论 ({{ totalComments }})</h3>

    <div class="comment-form">
      <el-input v-model="newComment.content" type="textarea" :rows="4" placeholder="写下您的评论..." resize="none" />
      <div class="comment-form-footer">
        <el-button type="primary" :loading="isSubmitting" @click="submitComment">
          {{ isSubmitting ? '提交中...' : '提交评论' }}
        </el-button>
      </div>
    </div>

    <!-- 评论列表区域 -->
    <el-tree v-if="treeData.length > 0" :data="treeData" :props="defaultProps" node-key="id" :default-expand-all="true"
      class="comment-tree">
      <template #default="{ data }">
        <div class="custom-tree-node">
          <div class="comment-content-wrapper" :class="{'deleted-comment': data.content === '该评论已被删除'}">
            <div class="comment-header">
              <div class="comment-author">
                <el-avatar :size="36" :src="data.userAvatar" :alt="data.userName || '匿名用户'">
                  {{ data.userName ? getInitials(data.userName) : '?' }}
                </el-avatar>
                <div class="author-info">
                  <span class="comment-author-name">{{ data.userName || '匿名用户' }}</span>
                  <span v-if="data.ipInfo" class="ip-location">
                    IP属地：{{ data.ipInfo.city }}
                  </span>
                </div>
              </div>
              <span class="comment-date">{{ data.createdTime }}</span>
            </div>
            <div class="comment-body" :class="{'deleted-comment-text': data.content === '该评论已被删除'}">{{ data.content }}</div>
            <div class="comment-actions">
              <el-button link type="primary" size="small" @click.stop="showReplyForm(data)">
                回复
              </el-button>
              <el-button link :type="isLiked(data.id) ? 'primary' : 'info'" size="small"
                @click.stop="handleLike(data.id)">
                <el-icon class="like-icon">
                  <svg viewBox="0 0 1024 1024" width="16" height="16">
                    <path fill="currentColor"
                      d="M885.9 533.7c16.8-22.2 26.1-49.4 26.1-77.7 0-44.9-25.1-87.4-65.5-111.1a67.67 67.67 0 0 0-34.3-9.3H572.4l6-122.9c1.4-29.7-9.1-57.9-29.5-79.4A106.62 106.62 0 0 0 471 99.9c-52 0-98 35-111.8 85.1l-85.9 311h-.3v428h472.3c9.2 0 18.2-1.8 26.5-5.4 47.6-20.3 78.3-66.8 78.3-118.4 0-12.6-1.8-25-5.4-37 16.8-22.2 26.1-49.4 26.1-77.7 0-12.6-1.8-25-5.4-37 16.8-22.2 26.1-49.4 26.1-77.7 0-12.6-2-25.1-5.6-37.1zM112 528v364c0 17.7 14.3 32 32 32h65V496h-65c-17.7 0-32 14.3-32 32z" />
                  </svg>
                </el-icon>
                {{ data.likeCount || 0 }}
              </el-button>
            </div>
          </div>
        </div>
      </template>
    </el-tree>
    <div v-else class="no-comments">
      <el-empty description="暂无评论，快来抢沙发吧！" />
    </div>

    <el-dialog v-model="replyDialogVisible" title="回复评论" width="500px" destroy-on-close>
      <el-input v-model="replyForm.content" type="textarea" :rows="4" placeholder="写下你的回复..." />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReply" :disabled="!replyForm.content.trim()">
            回复
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue';
import {
  ElTree,
  ElInput,
  ElButton,
  ElDialog,
  ElAvatar,
  ElIcon,
  ElEmpty,
  ElMessage
} from 'element-plus';
import { getCommentsById, like, addComment } from '../api/comments.js';
import { useTokenStore } from '../stores/index'
const tokenStore = useTokenStore();

const props = defineProps({
  postId: {
    type: Number,
    required: true
  }
});

const comments = ref([]);
// 获取评论的函数
const fetchComments = async () => {
  try {
    const res = await getCommentsById(props.postId);
    if (res.code === 200) {
      comments.value = res.data;
    }
  } catch (error) {
    console.error('获取评论失败:', error);
  }
};

// 监听 postId 变化
watch(() => props.postId, (newVal) => {
  if (newVal) {
    fetchComments();
  }
}, { immediate: true });

const emit = defineEmits(['add-reply']);

// 新评论表单
const newComment = reactive({
  content: ''
});

const isSubmitting = ref(false);

// 提交评论
const submitComment = () => {
  if (tokenStore.token === null) {
    ElMessage.error('请先登录');
    return;
  }
  if (!newComment.content.trim()) return;

  isSubmitting.value = true;

  const comment = {
    postId: props.postId,
    content: newComment.content,
    parentId: null,
  };
  // 这里应该调用后端 API
  addComment(comment).then(res => {
    if (res.code == 200) {
      fetchComments();
      newComment.content = '';
      isSubmitting.value = false;
      ElMessage.success('评论成功');
    } else {
      ElMessage.error('评论失败');
    }
  })

};

// 直接使用后端返回的树形数据
const treeData = computed(() => comments.value);

const defaultProps = {
  children: 'replies',  // 修改为 'replies' 以匹配后端数据结构
  label: 'content'
};

// 回复对话框
const replyDialogVisible = ref(false);
const replyForm = reactive({
  content: '',
  parentId: null,
  postId: props.postId
});

const showReplyForm = (comment) => {
  replyForm.parentId = comment.id;
  replyDialogVisible.value = true;
};

const submitReply = async () => {
  if (tokenStore.token == null || tokenStore.token == '') {
    ElMessage.error('请先登录');
    return;
  }
  if (!replyForm.content.trim()) return;

  try {
    const reply = {
      postId: props.postId,
      parentId: replyForm.parentId,
      content: replyForm.content,
    };
    // 这里应该调用后端 API
    addComment(reply).then(res => {
      if (res.code == 200) {
        replyDialogVisible.value = false;
        replyForm.content = '';
        ElMessage.success('回复成功');
        fetchComments(); // 刷新评论列表
      } else {
        ElMessage.error('回复失败');
      }
    });
  } catch (error) {
    ElMessage.error('回复失败');
  }
};

// 添加点赞状态管理
const likedComments = ref(new Set());

// 检查评论是否已被点赞
const isLiked = (commentId) => {
  return likedComments.value.has(commentId);
};

// 处理评论点赞
const handleLike = async (commentId) => {
  if (isLiked(commentId)) {
    return ElMessage.warning('您已经点过赞了');
  }

  try {
    await like(commentId, props.postId);  // 调用点赞 API
    likedComments.value.add(commentId);

    // 更新评论的点赞数
    const updateCommentLike = (comments) => {
      for (const comment of comments) {
        if (comment.id === commentId) {
          comment.likeCount = (comment.likeCount || 0) + 1;
          return true;
        }
        if (comment.replies && comment.replies.length > 0) {
          if (updateCommentLike(comment.replies)) {
            return true;
          }
        }
      }
      return false;
    };

    updateCommentLike(comments.value);
    ElMessage.success('点赞成功');
  } catch (error) {
    ElMessage.error('点赞失败');
  }
};

// 获取名字首字母作为头像
const getInitials = (name) => {
  if (!name) return '?';
  return name.charAt(0).toUpperCase();
};

// 计算总评论数，包括回复
const totalComments = computed(() => {
  const countReplies = (comments) => {
    let count = comments.length;
    for (const comment of comments) {
      if (comment.replies && comment.replies.length > 0) {
        count += countReplies(comment.replies);
      }
    }
    return count;
  };
  return countReplies(comments.value);
});
</script>

<style scoped>
.comment-section {
  max-width: 860px;
  margin: 0 auto;
}

.comment-tree {
  margin-top: 2rem;
}

.custom-tree-node {
  flex: 1;
  padding: 1rem 0;
}

.comment-content-wrapper {
  width: 100%;
  padding: 1rem;
  background: var(--el-bg-color-overlay);
  border-radius: 8px;
  transition: var(--el-transition-duration);
}

.comment-content-wrapper:hover {
  background: var(--el-fill-color-light);
}

.deleted-comment {
  background: var(--el-fill-color-lighter);
  opacity: 0.8;
}

.deleted-comment-text {
  color: var(--el-text-color-secondary);
  font-style: italic;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.comment-author {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

.author-info {
  display: flex;
  flex-direction: column;
  gap: 0.2rem;
}

.ip-location {
  font-size: 0.75rem;
  color: var(--el-text-color-secondary);
}

.comment-body {
  margin: 0.5rem 0;
  line-height: 1.6;
  color: var(--el-text-color-primary);
}

.comment-actions {
  margin-top: 0.5rem;
  display: flex;
  gap: 1rem;
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: 0.5rem 0;
  cursor: pointer;
  /* 添加指针样式 */
}

:deep(.el-tree-node__children) {
  padding-left: 2.5rem;
  position: relative;
}

:deep(.el-tree-node__children)::before {
  content: '';
  position: absolute;
  left: 1.25rem;
  top: 0;
  bottom: 0;
  width: 2px;
  background-color: var(--el-border-color-lighter);
}

:deep(.el-tree-node__expand-icon) {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  cursor: pointer;
  transition: transform 0.3s;
  margin-right: 8px;
  /* 添加右边距 */
}

:deep(.el-tree-node__expand-icon.expanded) {
  transform: rotate(90deg);
}

:deep(.el-avatar) {
  background: var(--el-color-primary);
}

.comment-form {
  margin: 2rem 0;
  padding: 1.5rem;
  background: var(--el-bg-color-overlay);
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
}

.comment-form-footer {
  margin-top: 1rem;
  text-align: right;
}

.no-comments {
  text-align: center;
  padding: 3rem 2rem;
  background-color: var(--color-card);
  border-radius: 12px;
  color: var(--color-text-light);
  font-size: 0.95rem;
}

.like-icon {
  margin-right: 4px;
}

:deep(.el-button.el-button--info) .like-icon,
:deep(.el-button.el-button--primary) .like-icon {
  transition: transform 0.2s;
}

:deep(.el-button.el-button--info:hover) .like-icon,
:deep(.el-button.el-button--primary:hover) .like-icon {
  transform: scale(1.2);
}

/* 优化嵌套层级的视觉样式 */
:deep(.el-tree-node) {
  position: relative;
  padding-left: 1rem;
}

/* 补充必要的 Element Plus 样式变量 */
:root {
  --el-transition-duration: 0.3s;
  --el-fill-color-light: #f5f7fa;
  --el-fill-color-lighter: #ebeef5;
  --el-text-color-primary: #303133;
  --el-text-color-secondary: #909399;
  --el-bg-color-overlay: #ffffff;
  --el-box-shadow-light: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
